<?php

namespace Aiweline\AiReviewForMagentoProduct\Console\Magento;

use Aiweline\Center\Helper\FeiShu;
use Aiweline\AiReviewForMagentoProduct\Lib\Magento\Config;
use Aiweline\AiReviewForMagentoProduct\Lib\Magento\Product;
use Weline\Cron\Helper\CronStatus;
use Weline\Framework\App\Env;
use Weline\Framework\Console\CommandInterface;

class Review implements CommandInterface
{

    function __construct(
        private \Aiweline\AiReviewForMagentoProduct\Helper\Config $config
    )
    {

    }

    public function tip(): string
    {
        return 'Import review to Magento. php 
        bin/w magento:review 
        params
         -model: ollama model name,
         -host: ollama host,
         -store_id: magento store id,
         -file: file path import by file,
         ';
    }

    public function execute(array $args = [], array $data = [])
    {
        $file = $args['file'] ?? '';
        $store_id = intval($args['store_id'] ?? $this->config->get('store_id') ?? 0);
        if ($file) {
            \Aiweline\AiReviewForMagentoProduct\Lib\Review::filePushToMagento($store_id, '氯化剂-评论.xlsx', [
                'store_url' => $this->config->get('host'),
            ]);
            return '文件导入成功！';
        }
        $model = $args['model'] ?? ($this->config->get('ollama_model') ?: 'deepseek-r1:1.5b');
        $host = $args['host'] ?? ($this->config->get('ollama_host') ?: 'http://127.0.0.1:11434');
        # 获取magento产品列表
        $page = 1;
        $pageSize = 100;
        $products = Product::all($store_id, $page, $pageSize);
        $total_count = $products['total_count'];
        if (!$total_count) {
            return 'No products found!';
        }
        $current = 1;
        foreach ($products['items'] as $product) {
            CronStatus::displayProgressBar('生成进度', $current, $total_count);
            $current++;
            $input = $this->getInput($product);
            $review = \Aiweline\AiReviewForMagentoProduct\Lib\ReviewGeneration::generate($input, $host, $model);
            if (!$review) {
                continue;
            }
            # 检测review中除了content_zh 字段，其他字段不能有中文文字
            if ($this->hasChinese($review)) {
                continue;
            }
            // 调用Magento API导入评论数据
            \Aiweline\AiReviewForMagentoProduct\Lib\Review::importReviewToMagento($store_id, $review);
        }
        if ($total_count > $pageSize) {
            $pageCount = ceil($total_count / $pageSize);
            for ($i = 2; $i <= $pageCount; $i++) {
                $products = Product::all($store_id, $i, $pageSize);
                $products = $products['items'];
                foreach ($products as $product) {
                    CronStatus::displayProgressBar('Create progress', $current, $total_count);
                    $current++;
                    $input = $this->getInput($product);
                    $review = \Aiweline\AiReviewForMagentoProduct\Lib\ReviewGeneration::generate($input, $host, $model);
                    if (!$review) {
                        continue;
                    }
                    # 检测review中除了content_zh 字段，其他字段不能有中文文字
                    if ($this->hasChinese($review)) {
                        continue;
                    }
                    // 调用Magento API导入评论数据
                    \Aiweline\AiReviewForMagentoProduct\Lib\Review::importReviewToMagento($store_id, $review);
                }
            }
        }
        return 'Import review to Magento success!';
    }

    /**
     * @param string $sku
     * @param string $url
     * @return string
     */
    public function getInput(array $product): string
    {
        $description = $this->getDescription($product);

        # $input = '（假设你是32b模型）,根据产品真实特点作为依据来进行评论';
        $input = $this->config->get('ai_script') ?: '你是一个很乐意评论的买家，经常购买各种产品做测评。你有10年以上的网购经历。
        评论语言为美式英语，请根据给定的产品信息生成一个真人英语评论，评论内容content_zh字段是将content翻译为中文。
        评论要求: 生成一个随机英文昵称；生成英文评论标题摘要。
        ';
        $input .= '评论场景为：你已经购买了产品，并使用了产品，现在对产品进行评价（好评,表示对产品、服务等等方面满意）。评价内容随意发挥，不要重复。' . PHP_EOL;
        $input .= '根据给出的产品详情依据是：---开始---' . $description . '---结束---' . PHP_EOL;
        $input .= '请你以json格式的数据结构返回，结构如下：' . PHP_EOL;
        $time = date('Y-m-d H:i:s');

        $url_key_item = array_filter($product['custom_attributes'], function ($item) {
            return $item['attribute_code'] == 'url_key';
        });
        $url_key_item = array_shift($url_key_item);
        $url = Config::url($url_key_item['value'] . '.html');

        $input .= '{
            "sku": "' . $product['sku'] . '",
            "product_name": "' . $product['name'] . '",
            "name": "用户名",
            "url": "' . $url . '",
            "title": "评论标题",
            "content": "评论内容",
            "content_zh": "中文评论内容",
            "time": "' . $time . '",
            "store_url": "https://www.trustonlines.com/",
            "store_id": "2"
       }';
        $input .= '返回内容只允许 json格式，请不要返回其他内容,json内部除了content_zh之外不能有中文。' . PHP_EOL;
        $input .= '请务必确认json格式正确，否则将无法正常解析。' . PHP_EOL;
        return $input;
    }

    /**
     * @param mixed $product
     * @return array
     */
    public function getDescription(mixed $product): string
    {
        $description = '--name:' . $product['name'] . PHP_EOL;
        $description .= '--sku:' . $product['name'] . PHP_EOL;
        $short_description_item = array_filter($product['custom_attributes'], function ($item) {
            return $item['attribute_code'] == 'short_description';
        });
        $short_description_item = array_shift($short_description_item);
        $short_description = $short_description_item['value'];
        $description .= '--short_description:' . $short_description . PHP_EOL;

        $description_item = array_filter($product['custom_attributes'], function ($item) {
            return $item['attribute_code'] == 'description';
        });
        $description_item = array_shift($description_item);
        $description .= '--description:' . $description_item['value'] . PHP_EOL;
        $description = strip_tags($description);
        return $description;
    }

    /**
     * @param mixed $review
     * @return void
     */
    public function hasChinese(mixed $review): bool
    {
        $has_zh = false;
        foreach ($review as $key => $value) {
            if (strpos($key, 'zh') !== false) {
                continue;
            }
            # 如果内容中有中文，则跳过
            if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $value)) {
                $has_zh = true;
                continue;
            }
        }
        return $has_zh;
    }
}